import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutterapp/src/utils/log_utils.dart';
import 'package:video_player/video_player.dart';

class VideoDetail2Widget extends StatefulWidget {
  final StreamController streamController;
  VideoDetail2Widget({this.streamController});

  @override
  _VideoDetail2WidgetState createState() => _VideoDetail2WidgetState();
}

class _VideoDetail2WidgetState extends State<VideoDetail2Widget> {
  VideoPlayerController _controller;
  bool _isPlay = false;
  @override
  void initState() {
    super.initState();
    // 视频播放控制器
    _controller = VideoPlayerController.asset("assets/video/list_item.mp4")
      ..initialize().then((_) {
        setState(() {});
      });
    // 监听视频播放
    _controller.addListener(() {
      if (_isPlay && !_controller.value.isPlaying) {
        _isPlay = false;
        setState(() {});
      }
      // 视频当前的进度 时间
      Duration totalDuration = _controller.value.duration;
      // 视频的总进度时间
      Duration currentDuration = _controller.value.position;
      // 滑动条的值
      _currentSlider =
          currentDuration.inMilliseconds / totalDuration.inMilliseconds;
      // 视频播放的时候实时刷新视图
      if (_opacity == 1) {
        // 使用streamController实现局部刷新
        _streamController.add(0);
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose();
    _streamController.close();
    if (_timer.isActive) {
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        //第一层的视频
        buildVideoWidget(),

        //第二层的控制按钮
        buildControllerWidget()
      ],
    );
  }

  Timer _timer;
  double _opacity = 1.0;
  bool _isFirst = true;
  buildControllerWidget() {
    return AnimatedOpacity(
      duration: Duration(milliseconds: 1200),
      opacity: _opacity,
      child: GestureDetector(
          onTap: () {
            setState(() {
              _opacity = 1.0;
            });

            //创建一个延时执行的定时 器
            _timer = Timer(Duration(seconds: 3), () {
              setState(() {
                _opacity = 0.0;
              });
            });
            LogUtils.e("点击了按钮 $_opacity");
          },
          child: Stack(children: [
            // 构造播放暂停按钮
            buildIconWidget(),
            // 构造标题
            buildTitleWidget(),
            // 构建滑动条
            buildSliderWidget(),
          ])),
    );
  }

  // 构建暂停播放按钮
  Widget buildIconWidget() {
    return Positioned.fill(
      child: Container(
        //0.3 的蓝色透明度
        color: Colors.blueGrey.withOpacity(0.5),
        //图标
        child: GestureDetector(
          onTap: controllerClickFunction,
          //层叠布局
          child: Stack(
            //子Widget居中对齐
            alignment: Alignment.center,
            children: [
              ClipOval(
                child: Container(
                  width: 54,
                  height: 54,
                  decoration: BoxDecoration(
                      gradient: RadialGradient(colors: [
                    Colors.black.withOpacity(0.3),
                    Colors.black.withOpacity(0.5),
                  ])),
                  child: Icon(
                    _controller.value.isPlaying
                        ? Icons.pause
                        : Icons.play_arrow_sharp,
                    size: 33,
                    color: Colors.white,
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 构建视频
  buildVideoWidget() {
    return Positioned.fill(
      child: GestureDetector(
        onTap: () {
          _controller.pause();
          _isPlay = false;
          setState(() {});
        },
        child: AspectRatio(
          aspectRatio: _controller.value.aspectRatio,
          child: VideoPlayer(_controller),
        ),
      ),
    );
  }

  void controllerClickFunction() {
    bool isPlaying = _controller.value.isPlaying;
    if (isPlaying) {
      //  如果视频播放，则暂停视频
      stopPlayVideo();
      // 如果计时器还在，则清除计时
      if (_timer.isActive) {
        _timer.cancel();
      }
    } else {
      //  如果视频没有播放，则播放视频
      startPlayVideo();
      //  创建一个延时执行的计时器
      _timer = Timer(Duration(seconds: 3), () {
        setState(() {
          _opacity = 0.0;
        });
      });
    }
  }

  startPlayVideo() {
    _isPlay = true;
    _isFirst = false;
    //发送消息
    //先暂停再播放
    if (widget.streamController != null) {
      widget.streamController.add(_controller);
    }
    //当前视频 播放的位置
    Duration postion = _controller.value.position;
    //视频的总长度
    Duration duration = _controller.value.duration;

    if (postion == duration) {
      //播放完毕 再点击播放时，当播放位置滑动到开始位置
      _controller.seekTo(Duration.zero);
    }
    //开始播放
    _controller.play();

    setState(() {});
  }

  stopPlayVideo() {
    //视频播放控制器停止播放
    _controller.pause();
    //变量标识
    _isPlay = false;
  }

  // 构建视频标题
  Widget buildTitleWidget() {
    return Positioned(
      top: 10,
      left: 10,
      right: 10,
      height: 44,
      child: Row(
        children: [
          Icon(Icons.one_k),
          Text(
            "GGB flutter 探险之路",
            style: TextStyle(
                color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  // 构建滑动条
  double _currentSlider = 1.0;
  StreamController<int> _streamController = new StreamController();
  buildSliderWidget() {
    LogUtils.e("构建底部导航栏");
    if (_isFirst) {
      return Container();
    }
    return StreamBuilder(
      stream: _streamController.stream,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return Positioned(
          bottom: 10,
          left: 10,
          right: 10,
          height: 50,
          child: Row(
            children: [
              Text(buildStartText(),
                  style: TextStyle(color: Colors.white, fontSize: 14)),
              Expanded(
                child: Slider(
                    value: _currentSlider,
                    min: 0.0,
                    max: 1.0,
                    inactiveColor: Colors.white,
                    activeColor: Colors.redAccent,
                    onChanged: (value) {
                      // 修复在控制条隐藏的时候，滑动条还可以滑动的bug
                      if (_opacity == 0.0) return;
                      // 这里拖动滑动条改变的时候
                      setState(() {
                        _currentSlider = value;
                      });
                      _controller.seekTo(_controller.value.duration * value);
                    }),
              ),
              Text(buildEndText(),
                  style: TextStyle(color: Colors.white, fontSize: 14)),
            ],
          ),
        );
      },
    );
  }

  String buildStartText() {
    // 视频当前播放进度
    Duration duration = _controller.value.position;
    int m = duration.inMinutes;
    int s = duration.inSeconds;
    String mStr = "$m";
    if (m < 10) {
      mStr = "0$m";
    }
    String sStr = "$s";
    if (s < 10) {
      sStr = "0$s";
    }
    return "$mStr:$sStr";
  }

  String buildEndText() {
    Duration duration = _controller.value.duration;
    int m = duration.inMinutes;
    int s = duration.inSeconds;
    String mStr = "$m";
    if (m < 10) {
      mStr = "0$m";
    }
    String sStr = "$s";
    if (s < 10) {
      sStr = "0$s";
    }
    return "$mStr:$sStr";
  }
}
